package edu.xmut.kakamusic.fragment.video;

import android.content.res.Configuration;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.listener.LockClickListener;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import java.util.List;
import java.util.Objects;

import edu.xmut.kakamusic.R;
import edu.xmut.kakamusic.base.BaseFragment;
import edu.xmut.kakamusic.utils.RequestUtils;

public class VideoDetailFragment extends BaseFragment {

    private StandardGSYVideoPlayer player;
    private GSYVideoOptionBuilder gsyVideoOptionBuilder;
    private OrientationUtils orientationUtils;
    private boolean isPlay;
    private boolean isPause;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_video_detail, container, false);
        Bundle bundle = getArguments();
        if (Objects.nonNull(bundle)) {
            String image = bundle.getString("image");
            String name = bundle.getString("name");
            String intro = bundle.getString("intro");
            String[] list = bundle.getStringArray("list");
            player = root.findViewById(R.id.player_detail);
            ImageView imageView = new ImageView(requireActivity());
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            Glide.with(root)
                    .load(RequestUtils.BASE_URL + image)
                    .into(imageView);
            // 设置视频title
            player.getTitleTextView().setVisibility(View.GONE);
            player.getBackButton().setVisibility(View.GONE);
            // 外部辅助旋转
            orientationUtils = new OrientationUtils(requireActivity(), player);
            // 初始化不打开屏幕旋转
            orientationUtils.setEnable(false);
            gsyVideoOptionBuilder = new GSYVideoOptionBuilder();
            String url = "https://vdn.jcrb.com/masvod/jcrbvideo/mas/public/2021/11/22/20211122_17d46c04502_r1_1500k.mp4";
            gsyVideoOptionBuilder.setThumbImageView(imageView)
                    .setIsTouchWiget(true)
                    .setRotateViewAuto(false)
                    .setLockLand(false)
                    .setAutoFullWithSize(false)
                    .setShowFullAnimation(false)
                    .setNeedLockFull(true)
                    .setUrl(url)
                    .setCacheWithPlay(false)
                    .setVideoTitle(name)
                    .setVideoAllCallBack(new GSYSampleCallBack() {
                        @Override
                        public void onPrepared(String url, Object... objects) {
                            super.onPrepared(url, objects);
                            // 开始播放了才全屏
                            orientationUtils.setEnable(true);
                            isPlay = true;
                        }

                        @Override
                        public void onQuitFullscreen(String url, Object... objects) {
                            super.onQuitFullscreen(url, objects);
                            if (Objects.nonNull(orientationUtils)) {
                                orientationUtils.backToProtVideo();
                            }
                        }

                    }).setLockClickListener(new LockClickListener() {
                        @Override
                        public void onClick(View view, boolean lock) {
                            if (Objects.nonNull(orientationUtils)) {
                                orientationUtils.setEnable(!lock);
                            }
                        }
                    }).build(player);

            player.getFullscreenButton().setOnClickListener(v -> {
                // 直接竖屏
                orientationUtils.resolveByClick();
                player.startWindowFullscreen(requireActivity(), true, true);
            });

            TabLayout tabLayout = root.findViewById(R.id.tabLayout_video_detail);
            ViewPager2 viewPager2 = root.findViewById(R.id.vp_video_detail);
            List<Fragment> fragmentList = List.of(new VideoIntroductionFragment(intro), new VideoListFragment(list, this));
            viewPager2.setAdapter(new FragmentStateAdapter(this) {
                @NonNull
                @Override
                public Fragment createFragment(int position) {
                    return fragmentList.get(position);
                }

                @Override
                public int getItemCount() {
                    return fragmentList.size();
                }
            });

            TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(tabLayout, viewPager2, (tab, position) -> {
                switch (position) {
                    case 0:
                        tab.setText("视频简介");
                        break;
                    case 1:
                        tab.setText("视频列表");
                        break;
                }
            });
            tabLayoutMediator.attach();

        }
        return root;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
        if (Objects.equals(keyEvent.getAction(), KeyEvent.ACTION_DOWN) && Objects.equals(keyCode, KeyEvent.KEYCODE_BACK)) {
            if (Objects.nonNull(orientationUtils)) {
                orientationUtils.backToProtVideo();
            }
            if (GSYVideoManager.backFromWindowFull(requireActivity())) {
                return true;
            }
        }
        return super.onKeyDown(keyCode, keyEvent);
    }

    @Override
    public void onPause() {
        player.getCurrentPlayer().onVideoPause();
        super.onPause();
        isPause = true;
    }

    @Override
    public void onResume() {
        player.getCurrentPlayer().onVideoResume();
        super.onResume();
        isPause = false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (isPlay) {
            player.getCurrentPlayer().release();
        }
        if (Objects.nonNull(orientationUtils)) {
            orientationUtils.releaseListener();
        }
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (isPlay && !isPause) {
            player.onConfigurationChanged(requireActivity(), newConfig, orientationUtils, true, true);
        }
    }

    public void playNewUrl(String url) {
        gsyVideoOptionBuilder.setUrl(url).build(player);
        player.startPlayLogic();
    }
}
